/**
 * iview table合并表格行
 * @param table 表格VUE实例对象
 * @param key 列KEY
 * @param fiexed 合并列固定 'left', false
 * 暂时只支持第一列合并
 */
export const rowSpanTable = (table, key, fiexed = false) => {
  const iviewFiexd = {
    left: '.ivu-table-fixed'
    // right: '.ivu-table-fixed-right',
  }
  const seletor = fiexed ? `${iviewFiexd[fiexed]} .ivu-table-row` : '.ivu-table-body .ivu-table-row'
  const rows = table.$el.querySelectorAll(seletor)
  const { data, columns } = table
  if (rows && data.length) {
    const colIndex = findIndex(columns, key)
    if (colIndex === -1) {
      return
    }
    let cols
    data.forEach((item, index) => {
      const td = rows[index].querySelector(`td:nth-child(${colIndex + 1})`)
      td.style.background = '#fff'
      if (item.rowspan) {
        td.setAttribute('rowspan', item.rowspan)
        cols = rows[index].children.length
      } else if (!item[key]) {
        if (rows[index].children.length === cols) {
          removeElement(td)
        }
      }
    })
  }
}

function findIndex (columns, key) {
  const allCols = getArray(columns)
  let result = -1
  allCols.forEach((item, index) => {
    if (item.key === key) {
      result = index
    }
  })
  return result
}
function getArray (columns, result = []) {
  columns.forEach(col => {
    if (col.children && col.children.length) {
      getArray(col.children, result)
    } else {
      result.push(col)
    }
  })
  return result
}
function removeElement (element) {
  const parentElement = element.parentNode
  if (parentElement) {
    parentElement.removeChild(element)
  }
}

/**
 * iview table对数据进行处理
 * @param key 列KEY
 * @param resData 需要处理的表格数据
 */
export const formatRowspanData = (key, resData) => {
  let store = []
  resData = resData || []
  resData.forEach((item, index) => {
    const storeBefore = store[store.length - 1]
    if (storeBefore) {
      if (storeBefore.key === item[key]) {
        store[store.length - 1] = {
          key: storeBefore.key,
          before: storeBefore.before,
          after: index + 1
        }
      } else {
        store.push({
          key: item[key],
          before: index,
          after: index + 1
        })
      }
    } else {
      store.push({
        key: item[key],
        before: 0,
        after: 1
      })
    }
  })
  let sliceArr = []
  store.forEach(item => {
    sliceArr.push(resData.slice(item.before, item.after))
  })
  let result = []
  sliceArr.forEach(item => {
    item.forEach((val, index) => {
      if (!index) {
        if (item.length > 1) {
          val.rowspan = item.length + ''
        }
      } else {
        val[key] = null
      }
    })
    result = result.concat(item)
  })
  return result
}
